<template>
    <div style="height: 600px;">
        <!-- 动态查询 -->
        <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
            <el-form-item label="菜单名称" prop="subjectName">
                <el-input v-model="queryParams.subjectName" placeholder="请输入菜单名称" clearable style="width: 220px"
                    @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['system:role:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
            </el-col>
            <el-row style="margin-left: 79%;">
                <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top"
                    v-if="search">
                    <el-button circle icon="Search" @click="toggleSearch()" />
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="刷新" placement="top">
                    <el-button circle icon="Refresh" @click="refresh()" />
                </el-tooltip>
            </el-row>
        </el-row>

        <!-- 表格数据 -->
        <el-table v-if="refreshTable" v-loading="loading" :data="roleList" row-key="menuId"
            :default-expand-all="isExpandAll" :tree-props="{ children: 'menus', hasChildren: 'hasChildren' }">
            <el-table-column prop="menuName" label="菜单名称" :show-overflow-tooltip="true" width="160"></el-table-column>
            <el-table-column prop="icon" label="图标" align="center" width="100">
                <template #default="scope">
                    <component :is="scope.row.icon" class="el-icon"></component>
                </template>
            </el-table-column>
            <el-table-column prop="perms" label="权限" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="menuId" label="编号" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="orderNo" label="菜单顺序" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="url" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="操作" align="center" width="210" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:menu:edit']">修改</el-button>
                    <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
                        v-hasPermi="['system:menu:add']">新增</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['system:menu:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form :rules="rules" ref="roleRef" :model="form">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="父级编号" prop="parentId">
                        <el-input v-model="form.parentId" placeholder="请输入父级编号" />
                    </el-form-item>
                </el-col>

                <el-col :span="24" v-if="form.menuType != 'F'">
                    <el-form-item label="菜单图标" prop="icon">
                        <el-input v-model="form.icon" placeholder="请输入图标图标" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="菜单名称" prop="menuName">
                        <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示排序" prop="orderNo">
                        <el-input-number v-model="form.orderNo" controls-position="right" :min="0" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item prop="url">
                        <template #label>
                            <span>
                                <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                组件路径
                            </span>
                        </template>
                        <el-input v-model="form.url" placeholder="请输入组件路径" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item prop="perms">
                        <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="100" />
                        <template #label>
                            <span>
                                <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                                    placement="top">
                                    <el-icon><question-filled /></el-icon>
                                </el-tooltip>
                                权限字符
                            </span>
                        </template>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="权限角色" prop="roleIds">
                        <el-select v-model="form.roleIds" multiple placeholder="请选择" style="width: 240px">
                            <el-option v-for="item in options" :key="item.roleIds" :label="item.nickname"
                                :value="item.roleIds" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { getMenuList, addMenu, upMenu, delMenu,getMenuById } from "@/api/admin/menu/index.js";
import { ref, onMounted, getCurrentInstance, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { nextTick } from 'vue';
const { proxy } = getCurrentInstance();

const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(false);
const refreshTable = ref(true);
//讲师表单
let form = ref({
    menuId: '',
    orderNo: '',
    url: '',
    menuName: '',
    parentId: '',
    icon: '',
    perms: '',
    roleIds: []
})
const options = [
    {
        roleIds: 1,
        nickname: '管理员',
    },
    {
        roleIds: 2,
        nickname: '讲师',
    },
    {
        roleIds: 3,
        nickname: '学生',
    }
]
//动态查询
const queryParams = ref({
    subjectName: ''
})

onMounted(() => {
    getList();
})
const rules = reactive({
    orderNo: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
    menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
    url: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '父级编号不能为空', trigger: 'blur' }],
    icon: [{ required: true, message: '图标不能为空', trigger: 'blur' }],
    perms: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }]
})
/** 展开/折叠操作 */
function toggleExpandAll() {
    refreshTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
        refreshTable.value = true;
    });
}

/** 查询菜单列表 */
function getList() {
    loading.value = true;
    getMenuList(queryParams.value).then(response => {
        roleList.value = response.data.obj;
        loading.value = false;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    queryParams.value.levelId = '';
    queryParams.value.subjectName = '';
    queryParams.value.lpId = '';
    handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
    delMenu(row.menuId).then(res => {
        if (res.data.code == 200) {
            getList()
            ElMessage.success('删除成功')
        }
    })
}

/** 重置新增的表单以及其他数据  */
function reset() {
    form = ref({
        menuId: undefined,
        orderNo: undefined,
        url: undefined,
        menuName: undefined,
        parentId: undefined,
        icon: undefined,
        perms: undefined,
        roleIds: []
    })
}
/** 添加菜单 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加菜单";
}
/** 修改菜单 */
function handleUpdate(row) {
    reset();
    const aaa = []
    getMenuById(row.menuId).then(response => {
        form.value = response.data.obj;
        form.value.menuId = response.data.obj.menuId
        response.data.obj.roleIds.forEach(arr => {
            aaa.push(arr.roId)
        });
        form.value.roleIds = aaa
        open.value = true;
        title.value = "修改菜单";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["roleRef"].validate(valid => {
        if (valid) {
            if (form.value.menuId != undefined) {
                upMenu(form.value).then(response => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addMenu(form.value).then(response => {
                    if (response.data.code == 200) {
                        ElMessage.success("新增成功");
                        open.value = false;
                        getList();
                    } else {
                        ElMessage.error(response.data.message)
                        open.value = false;
                        getList();
                    }
                });
            }
        }
    });
}
/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}

const props = defineProps({
    /* 是否显示检索条件 */
    showSearch: {
        type: Boolean,
        default: true,
    },
    /* 显隐列信息 */
    columns: {
        type: Array,
    },
    /* 是否显示检索图标 */
    search: {
        type: Boolean,
        default: true,
    },
    /* 显隐列类型（transfer穿梭框、checkbox复选框） */
    showColumnsType: {
        type: String,
        default: "checkbox",
    },
    /* 右外边距 */
    gutter: {
        type: Number,
        default: 10,
    },
})

const emits = defineEmits(['update:showSearch', 'queryTable']);

// 搜索
function toggleSearch() {
    if (showSearch.value == true) {
        showSearch.value = false
    } else {
        showSearch.value = true
    }
    emits("update:showSearch", !props.showSearch);
}

// 刷新
function refresh() {
    getList()
}
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

/* main-container全局样式 */
.app-container {
    padding: 20px;
}

label {
    font-weight: 700;
}
</style>